import logging

from fastapi import APIRouter, Depends
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from apps.tab_manage.models import Setting
from apps.tab_manage.response_model import SettingData, SettingDataPut
from common.response.response_schema import simple_response
from database.db_sql import get_db

router = APIRouter()


@router.get('')
async def get_settings(db: AsyncSession = Depends(get_db)):
    result = await db.execute(select(Setting).order_by(Setting.id))
    settings = result.scalars().all()  # 获取查询结果
    return simple_response(data=settings)


@router.get('/{key}')
async def get_setting_by_key(key: str, db: AsyncSession = Depends(get_db)):
    result = await db.execute(select(Setting).filter(Setting.key == key))
    setting = result.scalar_one_or_none()  # 获取单个结果或 None
    if not setting:
        return simple_response(code=404, msg="未找到设置项")
    return simple_response(data=setting)


@router.put('/{key}')
async def update_setting(key: str, setting_data: SettingDataPut, db: AsyncSession = Depends(get_db)):
    result = await db.execute(select(Setting).filter(Setting.key == key))
    setting = result.scalar_one_or_none()  # 获取单个结果或 None

    if not setting:
        return simple_response(code=404, msg="未找到设置项")

    # 更新设置
    setting.value = setting_data.value
    setting.description = setting_data.description
    setting.input_type = setting_data.input_type

    await db.commit()  # 使用异步提交
    return simple_response(code=200, data=setting)


@router.delete('/{id}')
async def delete_setting(id: int, db: AsyncSession = Depends(get_db)):
    # 使用 await 等待查询结果
    result = await db.execute(select(Setting).filter(Setting.id == id))
    setting = result.scalar_one_or_none()

    if not setting:
        return simple_response(code=404)

    await db.delete(setting)
    await db.commit()  # 使用异步提交
    return simple_response(code=204)


@router.post('')
async def add_setting(setting_data: SettingData, db: AsyncSession = Depends(get_db)):
    result = await db.execute(select(Setting).filter(Setting.key == setting_data.key))
    setting = result.scalar_one_or_none()

    if setting:
        return simple_response(code=400, detail="该设置已存在")

    new_setting = Setting(
        key=setting_data.key,
        value=setting_data.value,
        description=setting_data.description,
        input_type=setting_data.input_type,
    )

    try:
        db.add(new_setting)
        await db.commit()  # 提交事务
    except Exception as e:
        logging.error(f"添加设置时出错: {e}")
        await db.rollback()  # 回滚事务
        return simple_response(code=500, msg="添加设置失败")

    return simple_response(code=201, data=setting_data.model_dump())
